package com.mzy.linear_struct.hot100.链表;


/**
 * @Author: mizy3
 * @Date: 2024/09/12/下午8:21
 * @Description:
 */
public class Pro25K个一组翻转链表 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(-1, head);
        ListNode pre = dummy;
        ListNode end = dummy;
        // 因为对于end你已经在截取k长度的时候判定过了，如果不满足就会跳出，但是如果end长度为k的时候呢？
        while(end.next != null){
            // 不满足条件直接退出当前截取的循环，然后交给下面if判断跳出总的while循环
            for(int i = 0; i< k && end != null; i++){
                end = end.next;
            }
            if(end == null){
                break;
            }

            ListNode start = pre.next;
            ListNode nextStart = end.next;
            end.next = null;
            pre.next = reverseListNode(start);
            start.next = nextStart;
            pre = start;
            end = pre;
        }

        return dummy.next;
    }

    public ListNode reverseListNode(ListNode head){
        ListNode prev = null;
        while(head != null){
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }
    public static void main(String[] args) {
        ListNode node = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        new Pro25K个一组翻转链表().reverseKGroup(node, 2);
    }
}
























